//
//  LCTabBar.m
//  LookCoupons
//
//  Created by 明明方 on 2017/9/8.
//  Copyright © 2017年 明明方. All rights reserved.
//

#import "LCTabBar.h"
#import "LCTabBarButton.h"

@interface LCTabBar()

@property(nonatomic, strong) LCTabBarButton * selectedButton;

@end

@implementation LCTabBar


- (void)setItems:(NSArray *)items {
    _items = items;
    
    for (UIView * view in self.subviews) {
        [view removeFromSuperview];
    }
    //遍历模型数据，创建对应的TabBarButton
    
    for (UITabBarItem * item in _items) {
        LCTabBarButton * btn = [LCTabBarButton buttonWithType:UIButtonTypeCustom];
        //给按钮赋值模型，按钮的内容由模型决定
        btn.item = item;
        btn.tag = self.subviews.count;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        if (btn.tag == 0) { //选中第0个
            [self btnClick:btn];
        }
        [self addSubview:btn];
    }
}

//点击底部按钮时候调用
- (void)btnClick:(LCTabBarButton *)button {

    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
    
    //通知tabBarVC切换控制器
    if (_delegate && [_delegate respondsToSelector:@selector(clickBtn:)])
    {
        [self.delegate clickBtn:button.tag];
    }
}

-(void)layoutSubviews {
    [super layoutSubviews];
    CGFloat btnX = 0;
    CGFloat btnY = 0;
    CGFloat btnW = self.bounds.size.width/self.items.count;
    CGFloat btnH = self.bounds.size.height;
    int i = 0;
    //调整系统自带的TabBar上的按钮位置
    for (UIView * tabBarButton in self.subviews) {
        btnX = i * btnW;
        tabBarButton.frame = CGRectMake(btnX, btnY, btnW, btnH);
        i++;
    }
}

- (void)setSelectIndex:(NSInteger)selectIndex {
    _selectIndex = selectIndex;
    self.selectedButton.selected = NO;
    LCTabBarButton * button = [self.subviews objectAtIndex:selectIndex];
    button.selected = YES;
    self.selectedButton = button;
}

@end
